<?php
/**
*
* @package express
* @version $Id: index.php,v 1.038 2008/11/06 20:21:00 nedka Exp $
* @copyright (c) 2008 nedka (Nguyen Dang Khoa)
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/

/**
* KTVM Portal 1.0.x for phpBB3
* @author nedka
*
* For a special girl whom I met at the library of Lotus University, Vietnam
* "KTVM" means "Kinh Te Vi Mo" - name of the book which that girl likes to read
* This portal system is written by PHP code, love feeling and my heart :">
*/

/**
* @ignore
*/
define('IN_PHPBB', true);
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : './';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
include($phpbb_root_path . 'common.' . $phpEx);
include($phpbb_root_path . 'includes/functions_display.' . $phpEx);
include($phpbb_root_path . 'includes/bbcode.' . $phpEx);

// Start session management
$user->session_begin();
$auth->acl($user->data);
$user->setup();
$user->add_lang('mods/express');

// Ads ID
$ads_id = request_var('ads', 0);

// Begin check users' permissions...
// Get the list of list-able forums for blocks that using data from the board
if ($config['block_announcements'] || $config['block_latest_topics'] || $config['block_latest_posts'] || $config['block_top_topics'])
{
	$sql = 'SELECT forum_id
		FROM ' . FORUMS_TABLE;
	$result = $db->sql_query($sql);

	$list_forum_ids = array();
	while ($row = $db->sql_fetchrow($result))
	{
		if ($auth->acl_get('f_list', $row['forum_id']))
		{
			$list_forum_ids[] = $row['forum_id'];
		}
	}
	$db->sql_freeresult($result);
}

// Latest news
if ($config['block_latest_news'])
{
	$sql = 'SELECT article_id, article_cat, article_title, article_time
		FROM ' . EXPRESS_ARTICLES_TABLE . '
		ORDER BY article_time DESC';
	$result = $db->sql_query_limit($sql, $config['express_items_per_toplist']);

	while ($row = $db->sql_fetchrow($result))
	{
		$template->assign_block_vars('latest_news', array(
			'TITLE'	=> $row['article_title'],
			'TIME'	=> $user->format_date($row['article_time']),
			'URL'	=> append_sid("{$phpbb_root_path}express.$phpEx", 'cat=' . $row['article_cat'] . '&amp;mode=view&amp;article=' . $row['article_id']),
		));	
	}
	$db->sql_freeresult($result);
}

// Hot news
if ($config['block_hot_news'])
{
	$sql = 'SELECT article_id, article_cat, article_title, article_views, article_rates, article_ratings, article_comments
		FROM ' . EXPRESS_ARTICLES_TABLE . '
		WHERE article_views > 0
		ORDER BY article_rates DESC, article_ratings DESC, article_comments DESC, article_views DESC';
	$result = $db->sql_query_limit($sql, $config['express_items_per_toplist']);

	while ($row = $db->sql_fetchrow($result))
	{
		$template->assign_block_vars('hot_news', array(
			'TITLE'		=> $row['article_title'],
			'VIEWS'		=> $row['article_views'],
			'RATES'		=> $row['article_rates'] . '/10',
			'RATINGS'	=> $row['article_ratings'],
			'COMMENTS'	=> $row['article_comments'],
			'URL'		=> append_sid("{$phpbb_root_path}express.$phpEx", 'cat=' . $row['article_cat'] . '&amp;mode=view&amp;article=' . $row['article_id']),
		));	
	}
	$db->sql_freeresult($result);
}

// Latest announcements
if ($config['block_announcements'])
{
	$sql = 'SELECT topic_id, forum_id, topic_title, topic_time
		FROM ' . TOPICS_TABLE . '
		WHERE ' . $db->sql_in_set('forum_id', $list_forum_ids) . '
			AND topic_status = ' . ITEM_UNLOCKED . '
			AND topic_approved = 1
			AND topic_type IN (' . POST_GLOBAL . ', ' . POST_ANNOUNCE . ')
		ORDER BY topic_time DESC';
	$result = $db->sql_query_limit($sql, $config['express_items_per_toplist']);

	while ($row = $db->sql_fetchrow($result))
	{
		$template->assign_block_vars('announcements', array(
			'TITLE'	=> $row['topic_title'],
			'TIME'	=> $user->format_date($row['topic_time']),
			'URL'	=> append_sid("{$phpbb_root_path}viewtopic.$phpEx", 'f=' . $row['forum_id'] . '&amp;t=' . $row['topic_id']),
		));
	}
}

// Latest topics
// Do not display announcements if "Announcements" block is enabled
if ($config['block_latest_topics'])
{
	$sql = 'SELECT topic_id, forum_id, topic_title, topic_time
		FROM ' . TOPICS_TABLE . '
		WHERE ' . $db->sql_in_set('forum_id', $list_forum_ids) . '
			AND topic_status = ' . ITEM_UNLOCKED . '
			AND topic_approved = 1' .
			(($config['block_announcements']) ? ' AND topic_type IN (' . POST_NORMAL . ', ' . POST_STICKY . ')' : '') . '
		ORDER BY topic_time DESC';
	$result = $db->sql_query_limit($sql, $config['express_items_per_toplist']);

	while ($row = $db->sql_fetchrow($result))
	{
		$template->assign_block_vars('latest_topics', array(
			'TITLE'	=> $row['topic_title'],
			'TIME'	=> $user->format_date($row['topic_time']),
			'URL'	=> append_sid("{$phpbb_root_path}viewtopic.$phpEx", 'f=' . $row['forum_id'] . '&amp;t=' . $row['topic_id']),
		));
	}
}

// Latest posts
if ($config['block_latest_posts'])
{
	$sql = 'SELECT post_id, forum_id, post_subject, post_time
		FROM ' . POSTS_TABLE . '
		WHERE ' . $db->sql_in_set('forum_id', $list_forum_ids) . '
			AND post_approved = 1
		ORDER BY post_time DESC';
	$result = $db->sql_query_limit($sql, $config['express_items_per_toplist']);

	while ($row = $db->sql_fetchrow($result))
	{
		$template->assign_block_vars('latest_posts', array(
			'SUBJECT'	=> ($row['post_subject']) ? $row['post_subject'] : '',
			'TIME'		=> $user->format_date($row['post_time']),
			'URL'		=> append_sid("{$phpbb_root_path}viewtopic.$phpEx", 'p=' . $row['post_id'] . '#p' . $row['post_id']),
		));
	}
}

// Latest attachments
if ($config['block_latest_files'])
{
	$sql = 'SELECT attach_id, real_filename, attach_comment, filetime
		FROM ' . ATTACHMENTS_TABLE . '
		WHERE in_message = 0
			AND is_orphan = 0
			AND mimetype ' . $db->sql_like_expression(str_replace('*', $db->any_char, 'application/*')) . '
		ORDER BY filetime DESC';
	$result = $db->sql_query_limit($sql, $config['express_items_per_toplist']);

	while ($row = $db->sql_fetchrow($result))
	{
		$template->assign_block_vars('latest_files', array(
			'FILENAME'	=> ($row['real_filename']) ? $row['real_filename'] : '',
			'COMMENT'	=> ($row['attach_comment']) ? $row['attach_comment'] : '',
			'TIME'		=> $user->format_date($row['filetime']),
			'URL'		=> append_sid("{$phpbb_root_path}download/file.$phpEx", 'id=' . $row['attach_id']),
		));
	}
}

// Top topics by replies and views
if ($config['block_top_topics'])
{
	$sql = 'SELECT topic_id, forum_id, topic_title, topic_replies, topic_views
		FROM ' . TOPICS_TABLE . '
		WHERE ' . $db->sql_in_set('forum_id', $list_forum_ids) . '
			AND topic_status = ' . ITEM_UNLOCKED . '
			AND topic_approved = 1
		ORDER BY topic_replies DESC, topic_views DESC';
	$result = $db->sql_query_limit($sql, $config['express_items_per_toplist']);

	while ($row = $db->sql_fetchrow($result))
	{
		$template->assign_block_vars('top_topics', array(
			'TITLE'		=> $row['topic_title'],
			'REPLIES'	=> $row['topic_replies'],
			'VIEWS'		=> $row['topic_views'],
			'URL'		=> append_sid("{$phpbb_root_path}viewtopic.$phpEx", 'f=' . $row['forum_id'] . '&amp;t=' . $row['topic_id']),
		));
	}
}

// Top attachments
if ($config['block_top_files'])
{
	$sql = 'SELECT attach_id, real_filename, attach_comment, download_count
		FROM ' . ATTACHMENTS_TABLE . '
		WHERE in_message = 0
			AND is_orphan = 0
			AND download_count > 0
			AND mimetype ' . $db->sql_like_expression(str_replace('*', $db->any_char, 'application/*')) . '
		ORDER BY download_count DESC';
	$result = $db->sql_query_limit($sql, $config['express_items_per_toplist']);

	while ($row = $db->sql_fetchrow($result))
	{
		$template->assign_block_vars('top_files', array(
			'FILENAME'	=> ($row['real_filename']) ? $row['real_filename'] : '',
			'COMMENT'	=> ($row['attach_comment']) ? $row['attach_comment'] : '',
			'DOWNLOADS'	=> $row['download_count'],
			'URL'		=> append_sid("{$phpbb_root_path}download/file.$phpEx", 'id=' . $row['attach_id']),
		));
	}
}

// Newest users
if ($config['block_newest_users'])
{
	$sql = 'SELECT user_id, username, user_colour, user_regdate
		FROM ' . USERS_TABLE . '
		WHERE user_type IN (' . USER_NORMAL . ', ' . USER_FOUNDER . ')
		ORDER BY user_regdate DESC';
	$result = $db->sql_query_limit($sql, $config['express_items_per_toplist']);

	while ($row = $db->sql_fetchrow($result))
	{
		$template->assign_block_vars('newest_users', array(
			'USERNAME'	=> get_username_string('full', $row['user_id'], $row['username'], $row['user_colour']),
			'TIME'		=> $user->format_date($row['user_regdate']),
		));
	}
}

// Top posters
if ($config['block_top_posters'])
{
	$sql = 'SELECT user_id, username, user_colour, user_posts
		FROM ' . USERS_TABLE . '
		WHERE user_type IN (' . USER_NORMAL . ', ' . USER_FOUNDER . ')
			AND user_posts > 0
		ORDER BY user_posts DESC';
	$result = $db->sql_query_limit($sql, $config['express_items_per_toplist']);

	while ($row = $db->sql_fetchrow($result))
	{
		$template->assign_block_vars('top_posters', array(
			'USERNAME'	=> get_username_string('full', $row['user_id'], $row['username'], $row['user_colour']),
			'POSTS'		=> $row['user_posts'],
		));
	}
}

// Visited users on today
$visited_today_list = '';
if ($config['block_visited_today'])
{
	$sql = 'SELECT user_id, username, user_colour, user_lastvisit
		FROM ' . USERS_TABLE . '
		WHERE user_type IN (' . USER_NORMAL . ', ' . USER_FOUNDER . ')
			AND user_lastvisit > ' . (time() - (24 * 60 * 60)) . '
		ORDER BY user_lastvisit DESC';
	$result = $db->sql_query($sql);

	while ($row = $db->sql_fetchrow($result))
	{
		$visited_today_list .= (($visited_today_list != '') ? ', ' : '') . get_username_string('full', $row['user_id'], $row['username'], $row['user_colour']);
	}
	$db->sql_freeresult($result);
}

// Last visited bots
if ($config['block_last_visited_bots'])
{
	$sql = 'SELECT username, user_colour, user_lastvisit
		FROM ' . USERS_TABLE . '
		WHERE user_type = ' . USER_IGNORE . '
			AND user_lastvisit > 0
		ORDER BY user_lastvisit DESC';
	$result = $db->sql_query_limit($sql, $config['express_items_per_toplist']);

	while ($row = $db->sql_fetchrow($result))
	{
		$template->assign_block_vars('last_visited_bots', array(
			'NAME'	=> get_username_string('full', '', $row['username'], $row['user_colour']),
			'TIME'	=> $user->format_date($row['user_lastvisit']),
		));
	}
}

// Grab categories and articles
if ($config['block_express_cats'] && $config['num_express_articles'] > 0)
{
	$sql = 'SELECT *
		FROM ' . EXPRESS_CATEGORIES_TABLE . '
		WHERE cat_articles > 0
		ORDER BY cat_order';
	$result = $db->sql_query($sql);

	while ($row = $db->sql_fetchrow($result))
	{
		$template->assign_block_vars('cats', array(
			'CAT_ICON'			=> $phpbb_root_path . $config['express_icons_path'] . '/' . $row['cat_icon'],
			'CAT_NAME'			=> $row['cat_name'],
			'CAT_DESC'			=> $row['cat_desc'],
			'DISPLAY_ON_INDEX'	=> $row['display_on_index'],
			'CAT_URL'			=> append_sid("{$phpbb_root_path}express.$phpEx", 'cat=' . $row['cat_id']), 
			'CAT_FEED_RSS'		=> append_sid("{$phpbb_root_path}feed.$phpEx", 'type=express&amp;mode=rss&amp;cat=' . $row['cat_id']), 
			'CAT_FEED_ATOM'		=> append_sid("{$phpbb_root_path}feed.$phpEx", 'type=express&amp;mode=atom&amp;cat=' . $row['cat_id']), 
			'CAT_FEED_OPML'		=> append_sid("{$phpbb_root_path}feed.$phpEx", 'type=express&amp;mode=opml&amp;cat=' . $row['cat_id']), 

			'L_VIEW_ALL_CAT_ARTICLES'	=> sprintf($user->lang['VIEW_ALL_CAT_ARTICLES'], $row['cat_name']),

			'S_CAT_ICON'	=> ($row['cat_icon']) ? true : false,
		));

		if ($row['display_on_index'])
		{
			$sql2 = 'SELECT *
				FROM ' . EXPRESS_ARTICLES_TABLE . '
				WHERE article_cat = ' . $row['cat_id'] . '
				ORDER BY article_time DESC';
			$result2 = $db->sql_query_limit($sql2, $config['express_articles_per_cat']);

			while ($row2 = $db->sql_fetchrow($result2))
			{
				$template->assign_block_vars('cats.articles', array(	
					'ARTICLE_IMAGE'	=> $phpbb_root_path . $config['express_article_images_path'] . '/' . $row2['article_image'],
					'ARTICLE_TITLE'	=> $row2['article_title'],
					'ARTICLE_TIME'	=> $user->format_date($row2['article_time']),
					'ARTICLE_INTRO'	=> str_replace("\n", '<br />', $row2['article_intro']),
					'ARTICLE_URL'	=> append_sid("{$phpbb_root_path}express.$phpEx", 'cat=' . $row['cat_id'] . '&amp;mode=view&amp;article=' . $row2['article_id']), 

					'S_ARTICLE_IMAGE'	=> ($row2['article_image']) ? true : false,
				));	
			}
			$db->sql_freeresult($result2);
		}
	}
	$db->sql_freeresult($result);
}

// Grab blocks
if ($config['num_express_blocks'] > 0)
{
	$blocks = $cache->obtain_blocks();

	if (sizeof($blocks))
	{
		foreach ($blocks as $id => $data)
		{
			$block_ads_subtitle = ($config['block_express_ads'] && !empty($config['express_ads_contact'])) ? $user->lang['CALL'] . ' ' . $config['express_ads_contact'] : '';

			$template->assign_block_vars('blocks', array(
				'TYPE'		=> $data['type'],
				'ICON'		=> $phpbb_root_path . $config['express_icons_path'] . '/' . $data['icon'],
				'TITLE'		=> (!empty($user->lang[strtoupper($data['title'])])) ? $user->lang[strtoupper($data['title'])] : $data['title'],
				'SUB_TITLE'	=> ($data['type'] == 'express_ads' && $block_ads_subtitle) ? $block_ads_subtitle : ((!empty($user->lang[strtoupper($data['title']) . '_SUB'])) ? $user->lang[strtoupper($data['title']) . '_SUB'] : ''),
				'TEXT'		=> ($data['type'] == 'custom') ? generate_text_for_display($data['text'], $data['text_uid'], $data['text_bitfield'], $data['text_options']) : '',
 
				'S_ICON'				=> ($data['icon']) ? true : false,
				'S_BLOCK_LEFT'			=> ($data['position'] == BLOCK_LEFT) ? true : false,
				'S_BLOCK_RIGHT'			=> ($data['position'] == BLOCK_RIGHT) ? true : false,
				'S_BLOCK_TOP'			=> ($data['position'] == BLOCK_TOP) ? true : false,
				'S_BLOCK_BOTTOM'		=> ($data['position'] == BLOCK_BOTTOM) ? true : false,
				'S_BLOCK_MIDDLE_TOP'	=> ($data['position'] == BLOCK_MIDDLE_TOP) ? true : false,
				'S_BLOCK_MIDDLE_BOTTOM'	=> ($data['position'] == BLOCK_MIDDLE_BOTTOM) ? true : false,
			));
		}
	}
}

// Grab custom pages
if ($config['block_express_pages'] && $config['num_express_pages'] > 0)
{
	$sql = 'SELECT page_basename, page_name, page_icon
		FROM ' . EXPRESS_PAGES_TABLE . '
		ORDER BY page_basename';
	$result = $db->sql_query($sql);

	while ($row = $db->sql_fetchrow($result))
	{
		$template->assign_block_vars('pages', array(
			'ICON'	=> $phpbb_root_path . $config['express_icons_path'] . '/' . $row['page_icon'],
			'TITLE'	=> $row['page_name'],
			'URL'	=> append_sid("{$phpbb_root_path}content.$phpEx", 'page=' . strtolower($row['page_basename'])),

			'S_ICON'	=> ($row['page_icon']) ? true : false,
		));
	}
}

// Grab special articles
if ($config['block_special_articles'] && !empty($config['express_index_articles']))
{
	$sql = 'SELECT article_id, article_cat, article_title, article_intro
		FROM ' . EXPRESS_ARTICLES_TABLE . '
		WHERE article_id IN (' . $config['express_index_articles'] . ')
		ORDER BY article_time DESC';
	$result = $db->sql_query($sql);

	while ($row = $db->sql_fetchrow($result))
	{
		$template->assign_block_vars('special_articles', array(
			'TITLE'	=> $row['article_title'],
			'INTRO'	=> $row['article_intro'],
			'URL'	=> append_sid("{$phpbb_root_path}express.$phpEx", 'cat=' . $row['article_cat'] . '&amp;mode=view&amp;article=' . $row['article_id']),
		));
	}
}

// Grab advertisements
if ($config['block_express_ads'])
{
	$ads = $cache->obtain_ads();

	if (sizeof($ads))
	{
		foreach ($ads as $id => $data)
		{
			if ($data['display'])
			{
				if ($ads_id && $ads_id == $data['id'])
				{
					$sql = 'UPDATE ' . EXPRESS_ADS_TABLE . " SET ads_clicks = ads_clicks + 1 WHERE ads_id = $ads_id";
					$db->sql_query($sql);

					redirect($data['url'], false, true);
				}

				$template->assign_block_vars('ads', array(
					'IMAGE'		=> $phpbb_root_path . $config['express_ads_path'] . '/' . $data['img'],
					'WIDTH'		=> $data['width'],
					'HEIGHT'	=> $data['height'],
					'TITLE'		=> $data['title'],
					'URL'		=> append_sid("{$phpbb_root_path}index.$phpEx", 'ads=' . $data['id']),
					'TEXT'		=> str_replace("\n", '<br />', $data['text']),
				));
			}
		}
	}
}

// Grab navigation links
if ($config['block_express_links'])
{
	$links = $cache->obtain_links();

	if (sizeof($links))
	{
		foreach ($links as $id => $data)
		{
			$template->assign_block_vars('links', array(
				'ICON'	=> $phpbb_root_path . $config['express_icons_path'] . '/' . $data['icon'],
				'TITLE'	=> $data['title'],
				'URL'	=> $data['url'],

				'S_IS_CAT'	=> $data['is_cat'],
			));
		}
	}
}

// Grab group details for legend display
if ($auth->acl_gets('a_group', 'a_groupadd', 'a_groupdel'))
{
	$sql = 'SELECT group_id, group_name, group_colour, group_type
		FROM ' . GROUPS_TABLE . '
		WHERE group_legend = 1
		ORDER BY group_name ASC';
}
else
{
	$sql = 'SELECT g.group_id, g.group_name, g.group_colour, g.group_type
		FROM ' . GROUPS_TABLE . ' g
		LEFT JOIN ' . USER_GROUP_TABLE . ' ug
			ON (
				g.group_id = ug.group_id
				AND ug.user_id = ' . $user->data['user_id'] . '
				AND ug.user_pending = 0
			)
		WHERE g.group_legend = 1
			AND (g.group_type <> ' . GROUP_HIDDEN . ' OR ug.user_id = ' . $user->data['user_id'] . ')
		ORDER BY g.group_name ASC';
}
$result = $db->sql_query($sql);

$legend = '';
while ($row = $db->sql_fetchrow($result))
{
	$colour_text = ($row['group_colour']) ? ' style="color:#' . $row['group_colour'] . '"' : '';

	if ($row['group_name'] == 'BOTS')
	{
		$legend .= (($legend != '') ? ', ' : '') . '<span' . $colour_text . '>' . $user->lang['G_BOTS'] . '</span>';
	}
	else
	{
		$legend .= (($legend != '') ? ', ' : '') . '<a' . $colour_text . ' href="' . append_sid("{$phpbb_root_path}memberlist.$phpEx", 'mode=group&amp;g=' . $row['group_id']) . '">' . (($row['group_type'] == GROUP_SPECIAL) ? $user->lang['G_' . $row['group_name']] : $row['group_name']) . '</a>';
	}
}
$db->sql_freeresult($result);

// Generate birthday list if required ...
$birthday_list = '';
if ($config['load_birthdays'] && $config['allow_birthdays'])
{
	$now = getdate(time() + $user->timezone + $user->dst - date('Z'));
	$sql = 'SELECT user_id, username, user_colour, user_birthday
		FROM ' . USERS_TABLE . "
		WHERE user_birthday LIKE '" . $db->sql_escape(sprintf('%2d-%2d-', $now['mday'], $now['mon'])) . "%'
			AND user_type IN (" . USER_NORMAL . ', ' . USER_FOUNDER . ')';
	$result = $db->sql_query($sql);

	while ($row = $db->sql_fetchrow($result))
	{
		$birthday_list .= (($birthday_list != '') ? ', ' : '') . get_username_string('full', $row['user_id'], $row['username'], $row['user_colour']);

		if ($age = (int) substr($row['user_birthday'], -4))
		{
			$birthday_list .= ' (' . ($now['year'] - $age) . ')';
		}
	}
	$db->sql_freeresult($result);
}

// Animate Digits IP Tracking Counter
if ($config['block_counter'])
{
	include($phpbb_root_path . 'includes/functions_counter.' . $phpEx);
	$counter = new display_counter();

	// Counter display mode
	switch($config['counter_display_mode'])
	{
		case COUNTER_NONE:
			$counter = '';
		break;

		case COUNTER_IMAGE:
			$counter = $counter->create_output();
		break;

		case COUNTER_TEXT:
			$counter = $config['counter_hits'];
		break;
	}

	// Counter Statistics
	$counter_hours = (time() - $config['counter_startdate']) / 3600;
	$counter_days = (time() - $config['counter_startdate']) / 86400;
	$counter_weeks = (time() - $config['counter_startdate']) / 604800;
	$counter_months = (time() - $config['counter_startdate']) / 2592000;
	$counter_years = (time() - $config['counter_startdate']) / 31536000;

	$hits_per_user = sprintf('%.2f', $config['counter_hits'] / $config['num_users']);
	$hits_per_hour = sprintf('%.2f', $config['counter_hits'] / $counter_hours);
	$hits_per_day = sprintf('%.2f', $config['counter_hits'] / $counter_days);
	$hits_per_week = sprintf('%.2f', $config['counter_hits'] / $counter_weeks);
	$hits_per_month = sprintf('%.2f', $config['counter_hits'] / $counter_months);
	$hits_per_year = sprintf('%.2f', $config['counter_hits'] / $counter_years);

	if ($hits_per_user > $config['counter_hits'])
	{
		$hits_per_user = $config['counter_hits'];
	}

	if ($hits_per_hour > $config['counter_hits'])
	{
		$hits_per_hour = $config['counter_hits'];
	}

	if ($hits_per_day > $config['counter_hits'])
	{
		$hits_per_day = $config['counter_hits'];
	}

	if ($hits_per_week > $config['counter_hits'])
	{
		$hits_per_week = $config['counter_hits'];
	}

	if ($hits_per_month > $config['counter_hits'])
	{
		$hits_per_month = $config['counter_hits'];
	}

	if ($hits_per_year > $config['counter_hits'])
	{
		$hits_per_year = $config['counter_hits'];
	}
}

// Display forums from the board
if ($config['block_board'])
{
	display_forums('', false);
}

// Grab poll
if ($config['block_poll'] && !empty($config['block_poll_topic_id']))
{
	$user->add_lang('viewtopic');

	$voted_id = request_var('vote_id', array('' => 0));
	$view = request_var('view', '');
	$update = request_var('update', false);

	$sql = 'SELECT forum_id, topic_first_post_id, topic_status, poll_vote_change, poll_start, poll_length, poll_title, poll_max_options
		FROM ' . TOPICS_TABLE . '
		WHERE topic_id = ' . $config['block_poll_topic_id'];
	$result = $db->sql_query($sql);
	$row = $db->sql_fetchrow($result);
	$db->sql_freeresult($result);

	if ($row)
	{
		$poll_forum_id = (int) $row['forum_id'];
		$poll_post_id = (int) $row['topic_first_post_id'];
		$topic_status = (int) $row['topic_status'];
		$forum_status = $topic_status;// Not check forum status, because topic ID for this poll is selected by you from ACP :p
		$poll_vote_change = ($row['poll_vote_change']) ? true : false;
		$poll_start = (int) $row['poll_start'];
		$poll_length = (int) $row['poll_length'];
		$poll_title = (string) $row['poll_title'];
		$poll_max_options = (int) $row['poll_max_options'];
	}

	$sql = 'SELECT o.*, p.bbcode_bitfield, p.bbcode_uid
		FROM ' . POLL_OPTIONS_TABLE . ' o, ' . POSTS_TABLE . ' p
		WHERE o.topic_id = ' . $config['block_poll_topic_id'] . '
			AND p.post_id = ' . $poll_post_id . '
			AND p.topic_id = o.topic_id
		ORDER BY o.poll_option_id';
	$result = $db->sql_query($sql);

	$poll_info = array();
	while ($row = $db->sql_fetchrow($result))
	{
		$poll_info[] = $row;
	}
	$db->sql_freeresult($result);

	$cur_voted_id = array();
	if ($user->data['is_registered'])
	{
		$sql = 'SELECT poll_option_id
			FROM ' . POLL_VOTES_TABLE . '
			WHERE topic_id = ' . $config['block_poll_topic_id'] . '
				AND vote_user_id = ' . $user->data['user_id'];
		$result = $db->sql_query($sql);

		while ($row = $db->sql_fetchrow($result))
		{
			$cur_voted_id[] = $row['poll_option_id'];
		}
		$db->sql_freeresult($result);
	}
	else
	{
		// Cookie based guest tracking ... I don't like this but hum ho
		// it's oft requested. This relies on "nice" users who don't feel
		// the need to delete cookies to mess with results.
		if (isset($_COOKIE[$config['cookie_name'] . '_poll_' . $config['block_poll_topic_id']]))
		{
			$cur_voted_id = explode(',', $_COOKIE[$config['cookie_name'] . '_poll_' . $config['block_poll_topic_id']]);
			$cur_voted_id = array_map('intval', $cur_voted_id);
		}
	}

	$s_can_vote = (((!sizeof($cur_voted_id) && $auth->acl_get('f_vote', $poll_forum_id)) ||
		($auth->acl_get('f_votechg', $poll_forum_id) && $poll_vote_change)) &&
		(($poll_length != 0 && $poll_start + $poll_length > time()) || $poll_length == 0) &&
		$topic_status != ITEM_LOCKED &&
		$forum_status != ITEM_LOCKED) ? true : false;
	$s_display_results = (!$s_can_vote || ($s_can_vote && sizeof($cur_voted_id)) || $view == 'viewpoll') ? true : false;

	if ($update && $s_can_vote)
	{
		if (!sizeof($voted_id) || sizeof($voted_id) > $poll_max_options || in_array(VOTE_CONVERTED, $cur_voted_id))
		{
			$redirect_url = append_sid("{$phpbb_root_path}viewtopic.$phpEx", "f=$poll_forum_id&amp;t=" . $config['block_poll_topic_id'] . '&amp;start=0');

			meta_refresh(5, $redirect_url);

			if (!sizeof($voted_id))
			{
				$message = 'NO_VOTE_OPTION';
			}
			else if (sizeof($voted_id) > $poll_max_options)
			{
				$message = 'TOO_MANY_VOTE_OPTIONS';
			}
			else
			{
				$message = 'VOTE_CONVERTED';
			}
 
			$message = $user->lang[$message] . '<br /><br />' . sprintf($user->lang['RETURN_TOPIC'], '<a href="' . $redirect_url . '">', '</a>');
			trigger_error($message);
		}

		foreach ($voted_id as $option)
		{
			if (in_array($option, $cur_voted_id))
			{
				continue;
			}

			$sql = 'UPDATE ' . POLL_OPTIONS_TABLE . '
				SET poll_option_total = poll_option_total + 1
				WHERE poll_option_id = ' . (int) $option . '
					AND topic_id = ' . (int) $config['block_poll_topic_id'];
			$db->sql_query($sql);

			if ($user->data['is_registered'])
			{
				$sql_ary = array(
					'topic_id'			=> (int) $config['block_poll_topic_id'],
					'poll_option_id'	=> (int) $option,
					'vote_user_id'		=> (int) $user->data['user_id'],
					'vote_user_ip'		=> (string) $user->ip,
				);

				$sql = 'INSERT INTO ' . POLL_VOTES_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
				$db->sql_query($sql);
			}
		}

		foreach ($cur_voted_id as $option)
		{
			if (!in_array($option, $voted_id))
			{
				$sql = 'UPDATE ' . POLL_OPTIONS_TABLE . '
					SET poll_option_total = poll_option_total - 1
					WHERE poll_option_id = ' . (int) $option . '
						AND topic_id = ' . (int) $config['block_poll_topic_id'];
				$db->sql_query($sql);

				if ($user->data['is_registered'])
				{
					$sql = 'DELETE FROM ' . POLL_VOTES_TABLE . '
						WHERE topic_id = ' . (int) $config['block_poll_topic_id'] . '
							AND poll_option_id = ' . (int) $option . '
							AND vote_user_id = ' . (int) $user->data['user_id'];
					$db->sql_query($sql);
				}
			}
		}

		if ($user->data['user_id'] == ANONYMOUS && !$user->data['is_bot'])
		{
			$user->set_cookie('poll_' . $config['block_poll_topic_id'], implode(',', $voted_id), time() + 31536000);
		}

		$sql = 'UPDATE ' . TOPICS_TABLE . '
			SET poll_last_vote = ' . time() . '
			WHERE topic_id = ' . $config['block_poll_topic_id'];
		$db->sql_query($sql);

		$redirect_url = append_sid("{$phpbb_root_path}viewtopic.$phpEx", "f=$poll_forum_id&amp;t=" . $config['block_poll_topic_id'] . '&amp;start=0');

		meta_refresh(5, $redirect_url);
		trigger_error($user->lang['VOTE_SUBMITTED'] . '<br /><br />' . sprintf($user->lang['RETURN_TOPIC'], '<a href="' . $redirect_url . '">', '</a>'));
	}

	$poll_total = 0;
	foreach ($poll_info as $poll_option)
	{
		$poll_total += $poll_option['poll_option_total'];
	}

	if ($poll_info[0]['bbcode_bitfield'])
	{
		$poll_bbcode = new bbcode();
	}
	else
	{
		$poll_bbcode = false;
	}

	for ($i = 0, $size = sizeof($poll_info); $i < $size; $i++)
	{
		$poll_info[$i]['poll_option_text'] = censor_text($poll_info[$i]['poll_option_text']);

		if ($poll_bbcode !== false)
		{
			$poll_bbcode->bbcode_second_pass($poll_info[$i]['poll_option_text'], $poll_info[$i]['bbcode_uid'], $poll_option['bbcode_bitfield']);
		}

		$poll_info[$i]['poll_option_text'] = bbcode_nl2br($poll_info[$i]['poll_option_text']);
		$poll_info[$i]['poll_option_text'] = smiley_text($poll_info[$i]['poll_option_text']);
	}

	$poll_title = censor_text($poll_title);

	if ($poll_bbcode !== false)
	{
		$poll_bbcode->bbcode_second_pass($poll_title, $poll_info[0]['bbcode_uid'], $poll_info[0]['bbcode_bitfield']);
	}

	$poll_title = bbcode_nl2br($poll_title);
	$poll_title = smiley_text($poll_title);

	unset($poll_bbcode);

	foreach ($poll_info as $poll_option)
	{
		$option_pct = ($poll_total > 0) ? $poll_option['poll_option_total'] / $poll_total : 0;
		$option_pct_txt = sprintf("%.1d%%", ($option_pct * 100));

		$template->assign_block_vars('poll_option', array(
			'POLL_OPTION_ID' 		=> $poll_option['poll_option_id'],
			'POLL_OPTION_CAPTION' 	=> $poll_option['poll_option_text'],
			'POLL_OPTION_RESULT' 	=> $poll_option['poll_option_total'],
			'POLL_OPTION_PERCENT' 	=> $option_pct_txt,
			'POLL_OPTION_PCT'		=> round($option_pct * 100),
			'POLL_OPTION_IMG' 		=> $user->img('poll_center', $option_pct_txt, round($option_pct * 250)),
			'POLL_OPTION_VOTED'		=> (in_array($poll_option['poll_option_id'], $cur_voted_id)) ? true : false,
		));
	}

	$poll_end = $poll_length + $poll_start;

	// General viewtopic URL for return links
	$viewtopic_url = append_sid("{$phpbb_root_path}viewtopic.$phpEx", "f=$poll_forum_id&amp;t=" . $config['block_poll_topic_id'] . '&amp;start=0');

	$template->assign_vars(array(
		'POLL_QUESTION'			=> $poll_title,
		'TOTAL_VOTES' 			=> $poll_total,
		'POLL_LEFT_CAP_IMG'		=> $user->img('poll_left'),
		'POLL_RIGHT_CAP_IMG'	=> $user->img('poll_right'),

		'L_MAX_VOTES'	=> ($poll_max_options == 1) ? $user->lang['MAX_OPTION_SELECT'] : sprintf($user->lang['MAX_OPTIONS_SELECT'], $poll_max_options),
		'L_POLL_LENGTH'	=> ($poll_length) ? sprintf($user->lang[($poll_end > time()) ? 'POLL_RUN_TILL' : 'POLL_ENDED_AT'], $user->format_date($poll_end)) : '',

		'S_HAS_POLL'		=> true,
		'S_CAN_VOTE'		=> $s_can_vote,
		'S_DISPLAY_RESULTS'	=> $s_display_results,
		'S_IS_MULTI_CHOICE'	=> ($poll_max_options > 1) ? true : false,
		'S_POLL_ACTION'		=> $viewtopic_url,

		'U_VIEW_RESULTS'	=> $viewtopic_url . '&amp;view=viewpoll',
	));

	unset($poll_end, $poll_info, $voted_id);
}

// Get random quotes
if ($config['block_quotes'])
{
	$quotes = file($phpbb_root_path . 'language/ar/mods/quotes.txt'); 
	$i_quotes = sizeof($quotes) - 1; 
}

// Parse RSS sources
if ($config['block_rss'])
{
	include($phpbb_root_path . 'includes/rss_parser.' . $phpEx);
	$rss = new rss_parser;

	// Setup transparent cache
	$rss->cache_dir = $phpbb_root_path . 'cache'; 
	$rss->cache_time = $config['block_rss_time'] * 60;
	$rss->items_limit = $config['block_rss_limit'];

	// Get list of RSS publishers
	$rss_list = array_unique(explode(",", $config['block_rss_publishers']));

	for ($i = 0; $i < sizeof($rss_list); ++$i)
	{
		if ($publisher = $rss->get($rss_list[$i]))
		{
			$template->assign_block_vars('publisher', array(
				'TITLE'		=> (!empty($publisher['title'])) ? $publisher['title'] : '',
				'DESC'		=> (!empty($publisher['description'])) ? $publisher['description'] : '',
				'COPYRIGHT'	=> (!empty($publisher['copyright'])) ? $publisher['copyright'] : '',
				'URL'		=> (!empty($publisher['link'])) ? $publisher['link'] : '',
			));

			foreach($publisher['items'] as $item)
			{
				$template->assign_block_vars('publisher.rss', array(
					'TITLE'	=> (!empty($item['title'])) ? $item['title'] : '',
					'DESC'	=> (!empty($item['description'])) ? $item['description'] : '',				
					'TIME'	=> (!empty($item['pubDate'])) ? $item['pubDate'] : '',				
					'URL'	=> (!empty($item['link'])) ? $item['link'] : '',				
				));
			}
		}
	}
}

// Assign index specific vars
$template->assign_vars(array(
	'TOTAL_USERS'		=> $config['num_users'],
	'TOTAL_ARTICLES'	=> $config['num_express_articles'],
	'TOTAL_TOPICS'		=> $config['num_topics'],
	'TOTAL_POSTS'		=> $config['num_posts'],
	'TOTAL_FILES'		=> $config['num_files'],

	'LEGEND'				=> $legend,
	'BIRTHDAY_LIST'			=> $birthday_list,
	'VISITED_TODAY_LIST'	=> $visited_today_list,
	'QUOTES'				=> $quotes[rand(0, $i_quotes)],
	'AVATAR_IMG'			=> ($user->optionget('viewavatars')) ? get_user_avatar($user->data['user_avatar'], $user->data['user_avatar_type'], $user->data['user_avatar_width'], $user->data['user_avatar_height']) : '',
	'WELCOME_USERNAME'		=> get_username_string('full', $user->data['user_id'], $user->data['username'], $user->data['user_colour']),
	'COUNTER'				=> $counter,
	'COUNTER_STARTDATE'		=> sprintf($user->lang['COUNTER_STARTDATE'], $user->format_date($config['counter_startdate'], false, true)),
	'IP_TRACKING_INFO'		=> ($config['counter_block_ip']) ? $user->lang['IP_TRACKING_YES'] : $user->lang['IP_TRACKING_NO'],
	'HITS_PER_USER'			=> $hits_per_user,
	'HITS_PER_HOUR'			=> $hits_per_hour,
	'HITS_PER_DAY'			=> $hits_per_day,
	'HITS_PER_WEEK'			=> $hits_per_week,
	'HITS_PER_MONTH'		=> $hits_per_month,
	'HITS_PER_YEAR'			=> $hits_per_year,
	'PAYPAL_NAME'			=> $config['block_paypal_name'],
	'PAYPAL_EMAIL'			=> $config['block_paypal_email'],
	'PAYPAL_COUNTRY'		=> $config['block_paypal_country'],
	'SITE_URL'				=> $config['server_name'],

	'U_SEND_PASSWORD' 		=> ($config['email_enable']) ? append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=sendpassword') : '',
	'U_RESEND_ACTIVATION'	=> ($config['require_activation'] != USER_ACTIVATION_NONE && $config['email_enable']) ? append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=resend_act') : '',

	'S_LOGIN_ACTION'				=> append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=login'),
	'S_DISPLAY_BIRTHDAY_LIST'		=> ($config['load_birthdays']) ? true : false,
	'S_DISPLAY_VISITED_TODAY_LIST'	=> ($config['block_visited_today']) ? true : false,
	'S_DISPLAY_QUOTES'				=> ($config['block_quotes']) ? true : false,
	'S_COUNTER'						=> ($config['counter_display_mode'] == COUNTER_NONE) ? false : true,
	'S_COUNTER_IMAGE'				=> ($config['counter_display_mode'] == COUNTER_IMAGE) ? true : false,
	'S_COUNTER_TEXT'				=> ($config['counter_display_mode'] == COUNTER_TEXT) ? true : false,
	'S_COUNTER_STATS'				=> ($config['counter_display_stats']) ? true : false,
));

// Output page
page_header($user->lang['INDEX']);

$template->set_filenames(array(
	'body' => 'index_body.html')
);

page_footer();

?>